package com.behome.netty.netty_B.bean;


import com.behome.netty.common.ByteConventerKit;
import com.behome.netty.common.util.CRCKit;
import lombok.Data;

import java.nio.ByteBuffer;

@Data
public class ReBackPacketTail {
    public static final short LENGTH = 4;
    byte[] crc32;
    ReBackPacketHead head;
    ReBackPacketBody body;

    public ReBackPacketTail(ReBackPacketHead head, ReBackPacketBody body) {
        this.head = head;
        this.body = body;
    }

    public byte[] serialize() {
        return this.getCrc32Value();
    }

    private byte[] getCrc32Value() {
        if (this.head == null) {
            throw new IllegalArgumentException("head为空,不能生成校验数据");
        } else if (this.body == null) {
            throw new IllegalArgumentException("body为空,不能生成校验数据");
        } else {
            byte[] headData = this.head.serialize();
            byte[] bodyData = this.body.serialize();
            ByteBuffer byteBuffer = ByteBuffer.allocate(headData.length + bodyData.length);
            byteBuffer.put(headData).put(bodyData);
            this.crc32 = ByteConventerKit.intToBytes2(CRCKit.crc32Calc(byteBuffer.array()));
            return this.crc32;
        }
    }
}
